<template>
  <div class="g-page-container">
    <PageHeader title="法人信息" />
    <div class="g-content-container">
      <CorporateSearchForm
        ref="search-form"
        @search="loadTableList"
      />
      <ButtonGroup :options="middleButtons" @click="handleButtonClick" />
      <MainTableList
        :loading="loading"
        :data-source="dataSource"
        :columns="columns"
        slot-name="legalNo"
        :pagination="paginationMixin"
        :row-selection="rowSelectionMixin"
        @change="handleTableChange"
        @number-click="handleNumberClick"
      />
    </div>
    <component
      :is="currentComponent"
      :visible.sync="visibleDrawer"
      :corporate-id="corporateId"
      :route-data="routeData"
      @showEdit="changeEdit"
      @fresh="loadTableList"
    />
    <DrawerEditCorporate
      :visible.sync="showEdit"
      :corporate-id="corporateId"
      @fresh="loadTableList"
    />
    <DialogUploadCorporate
      ref="upload"
      @change="handleInsertChange"
      @load-table-list="loadTableList"
    />
  </div>
</template>

<script>
import CorporateSearchForm from './components/CorporateSearchForm.vue';
import mixinTable from '@/mixins/mixin-table.js';

import MainTableList from './components/mainTableList.vue';

import DrawerEditCorporate from './components/DrawerEditCorporate.vue';
import DrawerAddCorporate from './components/DrawerAddCorporate.vue';
import DrawerDetailCorporate from './components/DrawerDetailCorporate.vue';
import DialogUploadCorporate from '@/components/dialog/DialogUploadCorporate.vue';

import { postLegalByPage, postDownExcelImportTemplate, postLegalDelete } from '@/api/customerApi.js';
import { downloadFile } from '@/utils/index.js';

// import { CUSTOMER_NODE } from '@/constants/index';

export default {
  components: {
    CorporateSearchForm,
    MainTableList,
    DrawerDetailCorporate,
    DrawerEditCorporate,
    DrawerAddCorporate,
    DialogUploadCorporate
  },
  mixins: [mixinTable],
  data() {
    return {
      showEdit: false,
      routeData: {
        customerName: '',
        name: ''
      },
      currentComponent: '',
      asc: true,
      loading: false,
      dataSource: [],
      exportData: [],
      dateNeedList: [],
      isDateChange: false,
      columnKey: '',
      visibleDrawer: false,
      corporateId: undefined,
    };
  },
  computed: {
    middleButtons() {
      // const disabled = !this.rowSelectionMixin.selectedRowKeys.length;
      return [
        {
          key: 'add',
          type: 'primary',
          label: '新增',
          authKey: 'corporate-button-add',
        },
        {
          key: 'exportModal',
          label: '导出模板下载',
          authKey: 'corporate-button-export',
          // disabled,
        },
        {
          key: 'retweet',
          label: '批量导入',
          authKey: 'corporate-button-import',
          // disabled,
        },
        {
          key: 'delete',
          label: '删除',
          authKey: 'corporate-button-delete',
        },
      ];
    },

    columns() {
      const columns = [
        {
          align: 'center',
          title: '序号',
          dataIndex: 'dataIndex',
          width: 30,
          required: true,
          customRender: (t, r, index) => {
            return parseInt(index) + 1;
          },
        },
        {
          align: 'center',
          title: '法人编号',
          dataIndex: 'legalNo',
          key: 'legalNo',
          width: 120,
          sorter: true,
          required: true,
          scopedSlots: { customRender: 'legalNo' },
        },
        {
          align: 'center',
          title: '法人名称',
          dataIndex: 'legalName',
          key: 'legalName',
          width: 120,
          sorter: true,
          ellipsis: true,
        },
        {
          align: 'center',
          title: '客户名称',
          dataIndex: 'customerName',
          key: 'customerName',
          width: 100,
          sorter: true,
          ellipsis: true,
        },
        {
          align: 'center',
          title: '付款条件和账期',
          dataIndex: 'settlementPeriod',
          key: 'settlementPeriod',
          width: 100,
          sorter: true,
          ellipsis: true,
        },
        {
          align: 'center',
          title: '创建人',
          dataIndex: 'createUserName',
          key: 'createUserName',
          width: 80,
          sorter: true,
          ellipsis: true,
        },
        {
          align: 'center',
          title: '创建时间',
          dataIndex: 'createTime',
          key: 'createTime',
          width: 100,
          sorter: true,
          ellipsis: true,
        },
        {
          align: 'center',
          title: '最后修改人',
          dataIndex: 'updateUserName',
          key: 'updateUserName',
          width: 80,
          sorter: true,
          ellipsis: true,
        },
        {
          align: 'center',
          title: '最后修改时间',
          dataIndex: 'updateTime',
          key: 'updateTime',
          width: 120,
          sorter: true,
          ellipsis: true,
        },
      ];
      return columns;
    },
    escapeState() {
      return this.$store.state.dictionary.dict['state'] || {};
    },
  },
  created() {
    this.getCustomerListByPage();
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      if (to.query?.type === 'addCorporate' || to.query?.type === 'detailCorporate') {
        vm.handleNumberClick(to.query);
      }
    });
  },
  methods: {
    changeEdit(id) {
      this.corporateId = id
      this.showEdit = true
    },
    async getCustomerListByPage() {
      let data = this.$refs['search-form']?.getSearchParams;
      this.loading = true;
      try {
        const res = await postLegalByPage({
          ...data,
        });
        let dataList = res?.data?.data?.records;
        this.dataSource = dataList || [];
        this.paginationMixin.total = res?.data?.data?.total;
        this.loading = false;
      } catch (err) {
        console.log(err, 'err');
        this.loading = false;
      }
    },
    async handleNumberClick(record) {
      if (record.type === 'addCorporate') {
        this.currentComponent = 'DrawerAddCorporate';
        this.routeData.customerName = record.customerName;
        this.routeData.name = record.name;
        this.routeData.customerNo = record.customerNo;
      } else {
        this.currentComponent = 'DrawerDetailCorporate';
      }
      this.corporateId = record.id;
      this.visibleDrawer = true;
    },
    getSearchForm() {
      const form = this.$refs['search-form']?.getSearchParams || {};
      const page = {
        current: this.paginationMixin.current,
        pageSize: this.paginationMixin.pageSize,
        asc: this.asc,
        column: this.columnKey,
      };
      return { ...form, ...page };
    },
    async loadTableList() {
      let formData = this.getSearchForm();
      this.loading = true;
      const result = await postLegalByPage(formData).finally(
        () => (this.loading = false)
      );
      this.paginationMixin.total = result?.data?.data?.total || 0;
      this.dataSource = result?.data?.data?.records || [];
    },
    handleTableChange(page, filters, sorter, { currentDataSource }) {
      // console.log(page,sorter);
      this.asc = sorter.order === 'ascend' ? true : false;
      this.columnKey = sorter.columnKey;
      this.paginationMixin = page;
      this.loadTableList();
    },
    handleButtonClick(key) {
      // console.log(key);
      const fn = `${key}Callback`;
      this[fn] && this[fn]();
    },
    addCallback() {
      this.currentComponent = 'DrawerAddCorporate';
      this.visibleDrawer = true;
    },
    // 删除
    async deleteCallback() {
      let ids = this.rowSelectionMixin.selectedRowKeys || [];
      let res = await postLegalDelete(ids);
      if (res?.data?.code === 0) {
        this.$message.success('删除成功');
        this.loadTableList();
        this.rowSelectionMixin.selectedRowKeys = [];
      } else {
        this.$message.error('删除失败');
      }
    },
    // 出模板
    async exportModalCallback() {
      const res = await postDownExcelImportTemplate();
      await downloadFile(res.data, res.filename || '法人信息模板.xls');
    },
    // 批量导入
    async retweetCallback() {
      this.$refs.upload?.uploader();
    },
  },
};
</script>

<style lang="less" scoped>
.table-container {
  padding: 15px 20px;
  height: calc(100vh - 160px);
  box-sizing: border-box;
}
</style>
